Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(x/gov,x/distribution): Balance assertions on genesis import shouldn't be exact #22832

Open
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

fastfadingviolets
Copy link
Contributor

@fastfadingviolets fastfadingviolets commented Dec 11, 2024

Description

This PR fixes two assertions that are checked when a chain is restored from a genesis export. In both instances, a module's balance is expected to be exactly equal to its holdings in the chain. So the distribution module is expected to have the exact balance as the sum of all outstanding rewards, and governance is expected to have the exact sum of all proposal deposits. These assertions are often violated in practice, and it makes more sense to ensure that the balances are at least sufficient to cover the module holdings.


Author Checklist

All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.

I have...

  • included the correct type prefix in the PR title, you can find examples of the prefixes below:
  • confirmed ! in the type prefix if API or client breaking change
  • targeted the correct branch (see PR Targeting)
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • added a changelog entry to CHANGELOG.md
  • updated the relevant documentation or specification, including comments for documenting Go code
  • confirmed all CI checks have passed

Reviewers Checklist

All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.

Please see Pull Request Reviewer section in the contributing guide for more information on how to review a pull request.

I have...

  • confirmed the correct type prefix in the PR title
  • confirmed all author checklist items have been addressed
  • reviewed state machine logic, API design and naming, documentation is accurate, tests and test coverage

Summary by CodeRabbit

Release Notes

  • New Features

    • Added custom tally function in governance module.
    • Introduced new proposal types (optimistic, multiple choice).
    • Added MsgSudoExec message type.
  • Improvements

    • Enhanced balance verification in distribution and governance modules.
    • Added more detailed logging for proposal processes.
    • Introduced new governance parameters.
  • Breaking Changes

    • Updated method signatures in distribution and governance modules.
    • Modified error handling in genesis initialization.
    • Decoupled distribution module from protocol pool.
    • Updated CLI commands for reward withdrawals.
  • Bug Fixes

    • Addressed vulnerability in the distribution module.
  • Testing

    • Added comprehensive integration tests for distribution and governance modules.
    • Improved test coverage for import/export scenarios, including error handling for insufficient balances.

Copy link
Contributor

coderabbitai bot commented Dec 11, 2024

📝 Walkthrough

Walkthrough

This pull request introduces significant changes to the distribution and governance modules in the Cosmos SDK. The modifications focus on improving module interactions, error handling, and genesis state management. Key updates include decoupling the distribution module from the protocol pool, updating method signatures to accept strings instead of specific address types, and enhancing genesis import/export processes. The changes also introduce new testing mechanisms to validate module functionality, particularly around balance verification and proposal handling.

Changes

File Change Summary
x/distribution/CHANGELOG.md - Updated to reflect improvements in token handling
- Removed dependencies on x/protocolpool
- Modified method signatures and state management approaches
x/distribution/keeper/genesis.go - Updated error handling for balance verification
- Modified InitGenesis method to enforce stricter runtime checks
x/gov/CHANGELOG.md - Added new features like MaxVoteOptionsLen and custom tally function
- Introduced new proposal types and parameters
- Refactored address handling and module interactions
x/gov/genesis.go - Modified balance verification logic
- Updated error handling for module account balance
tests/integration/distribution/genesis_test.go - New integration test suite for distribution module
- Added tests for reward allocation and balance verification
tests/integration/v2/gov/genesis_test.go - Added test for insufficient balance scenarios
- Enhanced governance module import/export testing

Sequence Diagram

sequenceDiagram
    participant Module as Distribution Module
    participant Keeper as Module Keeper
    participant Genesis as Genesis Handler
    participant Account as Module Account

    Genesis->>Keeper: InitGenesis()
    Keeper->>Account: Verify Balance
    alt Insufficient Balance
        Keeper-->>Genesis: Return Error
    else Sufficient Balance
        Keeper->>Keeper: Process Genesis State
        Genesis-->>Keeper: Complete Initialization
    end
Loading

Possibly related PRs

Suggested Reviewers

  • tac0turtle
  • julienrbrt
  • facundomedica
  • akhilkumarpilli
  • sontrinh16

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions github-actions bot added C:x/gov C:x/distribution distribution module related labels Dec 11, 2024
@fastfadingviolets fastfadingviolets marked this pull request as ready for review December 11, 2024 15:35
x/gov/genesis.go Outdated
return fmt.Errorf("expected module account was %s but we got %s", balance.String(), totalDeposits.String())
// check if the module account can cover the total deposits
if !balance.IsAllGTE(totalDeposits) {
panic(fmt.Sprintf("expected module to hold at least %s, but it holds %s", totalDeposits, balance))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you still return an error here please

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh, of course, my bad

if !balances.Equal(moduleHoldingsInt) {
return fmt.Errorf("distribution module balance does not match the module holdings: %s <-> %s", balances, moduleHoldingsInt)
if balances.IsAllLT(moduleHoldingsInt) {
panic(fmt.Sprintf("distribution module balance is less than module holdings: %s < %s", balances, moduleHoldingsInt))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ditto

@julienrbrt julienrbrt changed the title Fix: Balance assertions on genesis import shouldn't be exact fix(x/gov,x/distribution): Balance assertions on genesis import shouldn't be exact Dec 11, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (2)
x/distribution/CHANGELOG.md (1)

Line range hint 1-1: Use standard Markdown strikethrough syntax.

For reverted changes, consider using the standard Markdown strikethrough syntax ~~text~~ instead of ~text~. This ensures better compatibility across different Markdown viewers.

Example:

-~The distribution module keeper now takes a new argument `PoolKeeper` in addition.~ Reverted on #20790
+~~The distribution module keeper now takes a new argument `PoolKeeper` in addition.~~ Reverted on #20790
x/distribution/keeper/genesis.go (1)

126-127: LGTM: Consistent balance check implementation

The implementation aligns well with the changes in the gov module. However, the error message could be more descriptive.

Consider enhancing the error message:

-		panic(fmt.Sprintf("distribution module balance is less than module holdings: %s < %s", balances, moduleHoldingsInt))
+		panic(fmt.Sprintf("distribution module balance insufficient - required: %s, actual: %s", moduleHoldingsInt, balances))
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 899099f and 5a4d71b.

📒 Files selected for processing (4)
  • x/distribution/CHANGELOG.md (1 hunks)
  • x/distribution/keeper/genesis.go (1 hunks)
  • x/gov/CHANGELOG.md (1 hunks)
  • x/gov/genesis.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
x/gov/genesis.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

x/distribution/keeper/genesis.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

x/distribution/CHANGELOG.md (1)

Pattern **/*.md: "Assess the documentation for misspellings, grammatical errors, missing documentation and correctness"

x/gov/CHANGELOG.md (1)

Pattern **/*.md: "Assess the documentation for misspellings, grammatical errors, missing documentation and correctness"

🔇 Additional comments (3)
x/distribution/CHANGELOG.md (1)

34-34: LGTM! The changelog entry is well-formatted and clear.

The entry follows the changelog format guidelines and accurately describes the change in balance assertions for genesis import.

x/gov/genesis.go (1)

82-84: LGTM: Balance check modification improves robustness

The change from exact balance matching to minimum balance requirement is a good improvement that maintains security while being more flexible.

Let's verify the consistency of this change with other modules:

✅ Verification successful

Balance check modification is consistent with other modules

The verification confirms that the balance check modification in x/gov/genesis.go is consistent with similar checks across the codebase:

  • In x/gov/keeper/invariants.go, the same IsAllGTE check is used for deposits validation
  • In x/distribution module, analogous checks using IsAllLT are implemented for module balances

The change maintains consistency with the existing patterns in the codebase while improving the robustness of the balance validation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for similar balance checks in other modules
rg -A 2 "balance.*IsAllGTE|balance.*IsAllLT" --type go

Length of output: 1027

x/gov/CHANGELOG.md (1)

41-41: LGTM: Clear and well-placed changelog entry

The changelog entry accurately describes the change and is correctly placed in the Improvements section.

Certain modules (e.g. ccvprovider) assign truncated fractions as
rewards, and transfer the full integer amount to the distribution
module. So a long-running chain will almost always fail the assertion if
the module holdings are expected to equal the balance
People will deposit tokens into gov for, for instance, ICAs, so we
really can't expect it to exactly equal the deposits.
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (1)
x/distribution/keeper/genesis.go (1)

126-127: LGTM! Balance check logic is improved.

The change correctly implements the requirement to ensure sufficient balance rather than exact balance. Consider making the error message more specific:

-		return fmt.Errorf("distribution module balance is less than module holdings: %s < %s", balances, moduleHoldingsInt)
+		return fmt.Errorf("%s module balance is less than module holdings: %s < %s", types.ModuleName, balances, moduleHoldingsInt)
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5a4d71b and 882b546.

📒 Files selected for processing (4)
  • x/distribution/CHANGELOG.md (1 hunks)
  • x/distribution/keeper/genesis.go (1 hunks)
  • x/gov/CHANGELOG.md (1 hunks)
  • x/gov/genesis.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • x/gov/genesis.go
  • x/distribution/CHANGELOG.md
🧰 Additional context used
📓 Path-based instructions (2)
x/distribution/keeper/genesis.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

x/gov/CHANGELOG.md (1)

Pattern **/*.md: "Assess the documentation for misspellings, grammatical errors, missing documentation and correctness"

🔇 Additional comments (2)
x/gov/CHANGELOG.md (1)

41-41: LGTM! Changelog entry is clear and well-placed.

The entry accurately reflects the changes being made to the governance module's balance assertions at genesis import.

x/distribution/keeper/genesis.go (1)

126-127: Add tests for the balance verification conditions.

Please add tests to verify both the success and failure cases of the balance verification logic.

@tac0turtle
Copy link
Member

i believe the code is correct, if you import a genesis file and the value is off then the genesis file could be providing in correct data. Or how do you see this being wrong in practice. I dont believe i have heard of a team running into this issue

@fastfadingviolets
Copy link
Contributor Author

i believe the code is correct, if you import a genesis file and the value is off then the genesis file could be providing in correct data. Or how do you see this being wrong in practice. I dont believe i have heard of a team running into this issue

it's not currently possible to import a genesis export from the cosmos hub because of these issues :) I believe there are two reasons this is happening

  1. The governance address is used for ICA, so has IBC tokens in excess of the deposits
  2. The ccvprovider module does a QuoTruncate when assigning rewards, so that the distribution module ends up with more tokens than the sum of rewards to consumer chain validators

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (3)
tests/integration/distribution/genesis_test.go (2)

3-25: Improve import organization for better readability

The imports should be grouped in the following order:

  1. Standard library
  2. External dependencies
  3. Internal dependencies
import (
	"encoding/json"
	"testing"

	abci "github.com/cometbft/cometbft/api/cometbft/abci/v1"
	"github.com/stretchr/testify/suite"

	corestore "cosmossdk.io/core/store"
	coretesting "cosmossdk.io/core/testing"
	"cosmossdk.io/depinject"
	"cosmossdk.io/log"
	sdkmath "cosmossdk.io/math"
	"cosmossdk.io/x/distribution/keeper"
	"cosmossdk.io/x/distribution/types"
	bankkeeper "cosmossdk.io/x/bank/keeper"
	stakingkeeper "cosmossdk.io/x/staking/keeper"

	"github.com/cosmos/cosmos-sdk/codec"
	"github.com/cosmos/cosmos-sdk/runtime"
	simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
	sdk "github.com/cosmos/cosmos-sdk/types"
	_ "github.com/cosmos/cosmos-sdk/x/auth"
	authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
)
🧰 Tools
🪛 golangci-lint (1.62.2)

6-6: File is not gci-ed with --skip-generated -s standard -s default -s prefix(cosmossdk.io) -s prefix(github.com/cosmos/cosmos-sdk) --custom-order

(gci)


11-11: File is not gci-ed with --skip-generated -s standard -s default -s prefix(cosmossdk.io) -s prefix(github.com/cosmos/cosmos-sdk) --custom-order

(gci)


15-15: File is not gci-ed with --skip-generated -s standard -s default -s prefix(cosmossdk.io) -s prefix(github.com/cosmos/cosmos-sdk) --custom-order

(gci)


20-20: File is not gci-ed with --skip-generated -s standard -s default -s prefix(cosmossdk.io) -s prefix(github.com/cosmos/cosmos-sdk) --custom-order

(gci)


175-188: Add documentation for the clearDB helper

Consider adding a comment explaining the purpose of this helper function and why it's necessary between tests.

+// clearDB removes all entries from the test database to ensure a clean state between tests.
 func (s *ImportExportSuite) clearDB(db corestore.KVStoreWithBatch) {
tests/integration/gov/genesis_test.go (1)

241-327: LGTM with suggestions for improvement

The new test case effectively validates the insufficient balance scenario. However, consider these improvements:

  1. The error assertion could be more specific to ensure the exact error condition is being tested
  2. Consider adding a test case for the boundary condition where the balance exactly equals the required amount

For the error assertion, consider:

-require.ErrorContains(t, err, "expected gov module to hold at least")
+expectedErr := fmt.Sprintf("expected gov module to hold at least %s, but only has %s", 
+    params.MinDeposit.String(),
+    sdk.Coins(params.MinDeposit).QuoInt(sdkmath.NewInt(2)).String())
+require.ErrorContains(t, err, expectedErr)
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 882b546 and 61a28aa.

📒 Files selected for processing (3)
  • tests/integration/distribution/genesis_test.go (1 hunks)
  • tests/integration/gov/genesis_test.go (3 hunks)
  • x/gov/genesis.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • x/gov/genesis.go
🧰 Additional context used
📓 Path-based instructions (2)
tests/integration/gov/genesis_test.go (3)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern tests/**/*: "Assess the integration and e2e test code assessing sufficient code coverage for the changes associated in the pull request"


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

tests/integration/distribution/genesis_test.go (3)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern tests/**/*: "Assess the integration and e2e test code assessing sufficient code coverage for the changes associated in the pull request"


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

🪛 golangci-lint (1.62.2)
tests/integration/distribution/genesis_test.go

6-6: File is not gci-ed with --skip-generated -s standard -s default -s prefix(cosmossdk.io) -s prefix(github.com/cosmos/cosmos-sdk) --custom-order

(gci)


11-11: File is not gci-ed with --skip-generated -s standard -s default -s prefix(cosmossdk.io) -s prefix(github.com/cosmos/cosmos-sdk) --custom-order

(gci)


15-15: File is not gci-ed with --skip-generated -s standard -s default -s prefix(cosmossdk.io) -s prefix(github.com/cosmos/cosmos-sdk) --custom-order

(gci)


20-20: File is not gci-ed with --skip-generated -s standard -s default -s prefix(cosmossdk.io) -s prefix(github.com/cosmos/cosmos-sdk) --custom-order

(gci)


104-104: ineffectual assignment to err

(ineffassign)


153-153: ineffectual assignment to err

(ineffassign)

🔇 Additional comments (4)
tests/integration/distribution/genesis_test.go (3)

27-65: LGTM! Well-structured test suite setup

The test suite setup is comprehensive and follows good practices:

  • Proper initialization of all required keepers
  • Clear dependency injection setup
  • Appropriate test address generation

67-124: LGTM! Comprehensive happy path test

The test effectively validates the new behavior where the distribution module can have more tokens than outstanding rewards.

🧰 Tools
🪛 golangci-lint (1.62.2)

104-104: ineffectual assignment to err

(ineffassign)


126-173: LGTM! Good negative test case

The test properly validates that genesis import fails when the module balance is insufficient to cover outstanding rewards.

🧰 Tools
🪛 golangci-lint (1.62.2)

153-153: ineffectual assignment to err

(ineffassign)

tests/integration/gov/genesis_test.go (1)

106-108: LGTM: Token transfer addition aligns with PR objectives

The addition of token transfer correctly simulates a scenario where the governance module has more tokens than required by deposits, which aligns with the PR's goal of relaxing exact balance requirements.

Comment on lines 104 to 112
app2, err := simtestutil.SetupWithConfiguration(
depinject.Configs(
AppConfig,
depinject.Supply(log.NewNopLogger()),
),
conf2,
)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix ineffectual error assignments in app setup

The error from SetupWithConfiguration is assigned but never checked.

 app2, err := simtestutil.SetupWithConfiguration(
   depinject.Configs(
     AppConfig,
     depinject.Supply(log.NewNopLogger()),
   ),
   conf2,
 )
+s.Require().NoError(err)

Also applies to: 153-160

🧰 Tools
🪛 golangci-lint (1.62.2)

104-104: ineffectual assignment to err

(ineffassign)

@@ -175,7 +179,7 @@ func TestImportExportQueues(t *testing.T) {
assert.Assert(t, proposal2.Status == v1.StatusVotingPeriod)

macc := s2.GovKeeper.GetGovernanceAccount(ctx2)
assert.DeepEqual(t, sdk.Coins(params.MinDeposit), s2.BankKeeper.GetAllBalances(ctx2, macc.GetAddress()))
assert.DeepEqual(t, sdk.Coins(params.MinDeposit).MulInt(sdkmath.NewInt(2)), s2.BankKeeper.GetAllBalances(ctx2, macc.GetAddress()))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Consider relaxing the exact balance assertion

The current assertion checks for an exact balance (2x minimum deposit), which appears to contradict the PR's objective of relaxing exact balance requirements. Consider modifying this to assert that the balance is greater than or equal to the required amount instead.

-assert.DeepEqual(t, sdk.Coins(params.MinDeposit).MulInt(sdkmath.NewInt(2)), s2.BankKeeper.GetAllBalances(ctx2, macc.GetAddress()))
+assert.Assert(t, s2.BankKeeper.GetAllBalances(ctx2, macc.GetAddress()).IsAllGTE(sdk.Coins(params.MinDeposit)))

Committable suggestion skipped: line range outside the PR's diff.

@tac0turtle
Copy link
Member

it's not currently possible to import a genesis export from the cosmos hub because of these issues :) I believe there are two reasons this is happening

  1. The governance address is used for ICA, so has IBC tokens in excess of the deposits
  2. The ccvprovider module does a QuoTruncate when assigning rewards, so that the distribution module ends up with more tokens than the sum of rewards to consumer chain validators

oof this is a bug in ica and ccvprovider. we can change it but teams have to stop doing stuff like this as its hacking the software and could introduce issues for other users. this is tricky, what is the reason you are exporting into a genesis file.

@fastfadingviolets
Copy link
Contributor Author

oof this is a bug in ica and ccvprovider. we can change it but teams have to stop doing stuff like this as its hacking the software and could introduce issues for other users. this is tricky, what is the reason you are exporting into a genesis file.

i'm part of the testing team for the hub; when there's a new version of gaia, we fork the cosmos hub from a genesis export and run the new version on the fork to check that the new binary works on mainnet.

fwiw i agree there's an issue in ccvprovider, but i do think the ica use case is reasonable as a way of having governance-gated holdings in a foreign token

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (1)
tests/integration/distribution/genesis_test.go (1)

67-125: LGTM! Comprehensive happy path test.

The test effectively verifies the new behavior allowing module balance to exceed total rewards. Consider adding test cases for edge cases where the balance is exactly equal to rewards.

// Add test case for exact balance match
rewards := sdk.NewDecCoinsFromCoins(sdk.NewCoin("stake", sdkmath.NewInt(33)))
err = s.BankKeeper.SendCoinsFromAccountToModule(ctx, s.addrs[0], types.ModuleName, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(33))))
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 61a28aa and 5534e4f.

📒 Files selected for processing (3)
  • tests/integration/distribution/genesis_test.go (1 hunks)
  • tests/integration/gov/genesis_test.go (3 hunks)
  • x/gov/genesis.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • x/gov/genesis.go
🧰 Additional context used
📓 Path-based instructions (2)
tests/integration/gov/genesis_test.go (3)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern tests/**/*: "Assess the integration and e2e test code assessing sufficient code coverage for the changes associated in the pull request"


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

tests/integration/distribution/genesis_test.go (3)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern tests/**/*: "Assess the integration and e2e test code assessing sufficient code coverage for the changes associated in the pull request"


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

🪛 golangci-lint (1.62.2)
tests/integration/distribution/genesis_test.go

6-6: File is not gci-ed with --skip-generated -s standard -s default -s prefix(cosmossdk.io) -s prefix(github.com/cosmos/cosmos-sdk) --custom-order

(gci)


11-11: File is not gci-ed with --skip-generated -s standard -s default -s prefix(cosmossdk.io) -s prefix(github.com/cosmos/cosmos-sdk) --custom-order

(gci)


15-15: File is not gci-ed with --skip-generated -s standard -s default -s prefix(cosmossdk.io) -s prefix(github.com/cosmos/cosmos-sdk) --custom-order

(gci)


20-20: File is not gci-ed with --skip-generated -s standard -s default -s prefix(cosmossdk.io) -s prefix(github.com/cosmos/cosmos-sdk) --custom-order

(gci)

🔇 Additional comments (5)
tests/integration/distribution/genesis_test.go (3)

1-66: LGTM! Well-structured test setup.

The test suite setup follows best practices with proper initialization, error handling, and test isolation.

🧰 Tools
🪛 golangci-lint (1.62.2)

6-6: File is not gci-ed with --skip-generated -s standard -s default -s prefix(cosmossdk.io) -s prefix(github.com/cosmos/cosmos-sdk) --custom-order

(gci)


11-11: File is not gci-ed with --skip-generated -s standard -s default -s prefix(cosmossdk.io) -s prefix(github.com/cosmos/cosmos-sdk) --custom-order

(gci)


15-15: File is not gci-ed with --skip-generated -s standard -s default -s prefix(cosmossdk.io) -s prefix(github.com/cosmos/cosmos-sdk) --custom-order

(gci)


20-20: File is not gci-ed with --skip-generated -s standard -s default -s prefix(cosmossdk.io) -s prefix(github.com/cosmos/cosmos-sdk) --custom-order

(gci)


127-175: LGTM! Good error case coverage.

The test effectively verifies that the system properly handles and reports insufficient module balance scenarios.


177-190: LGTM! Well-implemented helper function.

The clearDB function properly handles database cleanup with appropriate error handling and resource management.

tests/integration/gov/genesis_test.go (2)

106-109: LGTM! Good test coverage for excess balance scenario.

The added code properly simulates the scenario where the governance module has more tokens than required by deposits.


241-327: LGTM! Comprehensive test for insufficient balance scenario.

The test effectively verifies that genesis import fails when the governance module has insufficient funds to cover deposits.

@tac0turtle
Copy link
Member

i'm part of the testing team for the hub; when there's a new version of gaia, we fork the cosmos hub from a genesis export and run the new version on the fork to check that the new binary works on mainnet.

oh you dont have to do this anymore. We have documentation on how to avoid it: https://docs.cosmos.network/main/build/building-apps/app-testnet, its way faster too.

i agree we should fix the issue you opened, but there shouldnt be a need to export genesis anymore imo

@fastfadingviolets
Copy link
Contributor Author

oh you dont have to do this anymore. We have documentation on how to avoid it: https://docs.cosmos.network/main/build/building-apps/app-testnet, its way faster too.

i agree we should fix the issue you opened, but there shouldnt be a need to export genesis anymore imo

aha, so we're doing this as a workaround because we're not able to use the testnet stuff that's built-in :( i think the issue is that we can't change the chain-id (and this does give us more flexibility in terms of being able to change the genesis file when we start a fork)

@julienrbrt julienrbrt added the backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release label Dec 16, 2024
@julienrbrt
Copy link
Member

Could you fix the conflicts?

@facundomedica
Copy link
Member

Is this ready to merge?

@fastfadingviolets
Copy link
Contributor Author

Is this ready to merge?

yep, if it looks good to yall. i fixed the merge conflicts

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (6)
tests/integration/v2/gov/genesis_test.go (1)

168-230: Good test coverage, consider enhancing error validation

The test effectively validates the insufficient balance scenario, which is crucial for the PR's objective. However, consider these enhancements:

  1. Add assertions to verify the intermediate state after sending coins from the governance module (around line 192)
  2. Validate the specific error message content more thoroughly beyond just the prefix

Example enhancement:

 err = s1.BankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, addrs[0], sdk.Coins(params.MinDeposit).QuoInt(sdkmath.NewInt(2)))
 require.NoError(t, err)
+
+// Verify intermediate state
+macc := s1.GovKeeper.GetGovernanceAccount(ctx)
+balance := s1.BankKeeper.GetAllBalances(ctx, macc.GetAddress())
+require.True(t, balance.IsAllLT(sdk.Coins(params.MinDeposit)), "governance account balance should be less than minimum deposit")
+
 authGenState, err := s1.AuthKeeper.ExportGenesis(ctx)
tests/integration/distribution/genesis_test.go (5)

27-38: Add documentation for the test suite

Consider adding a doc comment explaining the purpose of this test suite and its role in validating genesis import/export functionality, particularly around balance assertions.


46-46: Document the significance of the token amount

The value 42 appears to be a magic number. Consider either documenting why this specific value was chosen or using a named constant.

-valTokens := sdk.TokensFromConsensusPower(42, sdk.DefaultPowerReduction)
+// Using 42 as a reasonable amount that ensures sufficient voting power for testing
+const testValidatorTokens = 42
+valTokens := sdk.TokensFromConsensusPower(testValidatorTokens, sdk.DefaultPowerReduction)

67-95: Enhance test assertions for module balance

The test verifies validator rewards but doesn't assert the final module balance. Consider adding balance verification to ensure complete test coverage.

+// Verify final module balance
+moduleAddr := s.AccountKeeper.GetModuleAddress(types.ModuleName)
+moduleBalance := s.BankKeeper.GetAllBalances(ctx, moduleAddr)
+s.Require().Equal(
+    sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(34))),
+    moduleBalance,
+    "unexpected module balance",
+)

127-139: Enhance test documentation and error handling

The test setup could be more explicitly documented to clarify the expected failure scenario. Consider adding a detailed comment explaining why 35 tokens of rewards with only 34 tokens in the module should fail.

+// TestInsufficientFunds verifies that genesis import fails when the distribution
+// module balance (34 tokens) is less than the total outstanding rewards (35 tokens).
+// This aligns with the requirement that the module must have sufficient funds to
+// cover all outstanding rewards.
 func (s *ImportExportSuite) TestInsufficientFunds() {

177-190: Document helper method and consider batch operations

  1. Add documentation explaining the purpose and importance of clearing the database between tests.
  2. Consider using batch operations for better performance when deleting multiple keys.
+// clearDB removes all entries from the test database to ensure a clean state
+// between test runs. This prevents any potential state leakage that could
+// affect test results.
 func (s *ImportExportSuite) clearDB(db corestore.KVStoreWithBatch) {
     iter, err := db.Iterator(nil, nil)
     s.Require().NoError(err)
     defer iter.Close()
 
     var keys [][]byte
     for ; iter.Valid(); iter.Next() {
         keys = append(keys, iter.Key())
     }
 
+    batch := db.NewBatch()
     for _, k := range keys {
-        s.Require().NoError(db.Delete(k))
+        s.Require().NoError(batch.Delete(k))
     }
+    s.Require().NoError(batch.Write())
 }
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bafd07a and 1fbcb24.

📒 Files selected for processing (6)
  • tests/integration/distribution/genesis_test.go (1 hunks)
  • tests/integration/v2/gov/genesis_test.go (3 hunks)
  • x/distribution/CHANGELOG.md (1 hunks)
  • x/distribution/keeper/genesis.go (1 hunks)
  • x/gov/CHANGELOG.md (1 hunks)
  • x/gov/genesis.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • x/gov/genesis.go
  • x/distribution/keeper/genesis.go
  • x/distribution/CHANGELOG.md
  • x/gov/CHANGELOG.md
🧰 Additional context used
📓 Path-based instructions (2)
tests/integration/distribution/genesis_test.go (3)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern tests/**/*: "Assess the integration and e2e test code assessing sufficient code coverage for the changes associated in the pull request"


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

tests/integration/v2/gov/genesis_test.go (3)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern tests/**/*: "Assess the integration and e2e test code assessing sufficient code coverage for the changes associated in the pull request"


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

🪛 golangci-lint (1.62.2)
tests/integration/distribution/genesis_test.go

6-6: File is not gci-ed with --skip-generated -s standard -s default -s prefix(cosmossdk.io) -s prefix(github.com/cosmos/cosmos-sdk) --custom-order

(gci)


11-11: File is not gci-ed with --skip-generated -s standard -s default -s prefix(cosmossdk.io) -s prefix(github.com/cosmos/cosmos-sdk) --custom-order

(gci)


15-15: File is not gci-ed with --skip-generated -s standard -s default -s prefix(cosmossdk.io) -s prefix(github.com/cosmos/cosmos-sdk) --custom-order

(gci)


20-20: File is not gci-ed with --skip-generated -s standard -s default -s prefix(cosmossdk.io) -s prefix(github.com/cosmos/cosmos-sdk) --custom-order

(gci)

🔇 Additional comments (2)
tests/integration/v2/gov/genesis_test.go (2)

63-65: LGTM: Well-implemented simulation of excess balance

The added code effectively simulates a real-world scenario where the governance module account holds more tokens than the required deposits, which aligns with the PR's objective of making balance assertions more flexible.


126-126: LGTM: Balance assertion correctly updated

The assertion has been properly updated to expect double the minimum deposit amount, which correctly validates the state after the additional token transfer to the governance account.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release C:x/distribution distribution module related C:x/gov
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants